﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextStream>
#include <QDebug>
#include <QTextEdit>
#include <QDebug>
#include <QDateTime>

static QString fileData;
static QString filePathOutput = "data.txt";
static QString filePathpmOutput = "dataPM.txt";
static QString filePathInput = "common.json";
static QString headerFile = "PF_Common.h";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("HMIControlBox");
    init();
}

MainWindow::~MainWindow()
{
    delete ui;
}

/*解析配置文件,类似dbc文件,供画面显示*/
void MainWindow::init()
{    
    _smallTool = new SmallTool();
    connect(_smallTool, &SmallTool::sendParseResult, this, &MainWindow::handleParseResult);

    m_timer = new QTimer;
    m_timer->setInterval(100);
    connect(m_timer, &QTimer::timeout, this, [=](){
        on_pushButton_clicked();
    });
    //
    ui->tableWidget->setColumnCount(3);

    QStringList heads;
    heads<<"信号"<<"bits"<<"值";
    ui->tableWidget->setHorizontalHeaderLabels(heads);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->setRowCount(0);

    //init lineEdit 结构体名字搜索框
    connect(ui->lineEdit, &QLineEdit::textChanged, this, [=](QString text){
        ui->listWidget->clear();
        if(text.trimmed().isEmpty()){
            QList<QString> keys = _name_to_id.keys();
            foreach (QString key, keys) {
                ui->listWidget->addItem(key+":"+QString::number(_name_to_id.value(key)));
            }
        }
        else{
            QList<QString> keys = _name_to_id.keys();
            foreach (QString key, keys) {
                if(key.contains(text.toLower()) || key.contains(text.toUpper())){
                    ui->listWidget->addItem(key+":"+QString::number(_name_to_id.value(key)));
                }
            }
        }
    });

    //init pm btn
    connect(ui->pushButton_2, &QPushButton::clicked, this, [=](){
//        ui->comboBox_2->setCurrentIndex(0);
        _currentPM = 0;
    });
    connect(ui->pushButton_3, &QPushButton::clicked, this, [=](){
//        ui->comboBox_2->setCurrentIndex(1);
        _currentPM = 1;
    });
    connect(ui->pushButton_4, &QPushButton::clicked, this, [=](){
//        ui->comboBox_2->setCurrentIndex(2);
        _currentPM = 2;
    });

    _currentPM = 0;
    //add edit
    _edit_form = new edit_form();
    _dialog_Help = new Dialog_Help(this);
    _dialog_Config = new Dialog_Config(this);
//    connect(_edit_form, &edit_form::sendParseResult, this, &MainWindow::handleParseResult);

    fileData = _smallTool->readFile(filePathInput);
    if(fileData.isEmpty())
    {
        qDebug()<<"找不到"<<filePathInput; //需要生成
        _smallTool->parseFile(headerFile);
        return;
    }
    readCommonJson(fileData);
    qDebug()<<"init over!"<<QDateTime::currentDateTime();
}

void MainWindow::showData()
{
    int len = _parseHeadMsgList.length();
    for(int i=0; i<len; i++){
        ui->listWidget->addItem(_parseHeadMsgList.at(i).toMap().value("name").toString()+":"+_parseHeadMsgList.at(i).toMap().value("id").toString());
    }
    ui->tableWidget->setRowCount(0);
}

void MainWindow::readCommonJson(QString data)
{
    _parseHeadMsgList = QJsonDocument::fromJson(data.toUtf8()).toVariant().toList();

    changeNameToId();

    showData();
}

void MainWindow::saveCommonJson()
{
    QString data = QString(QJsonDocument::fromVariant(_parseHeadMsgList).toJson());
    _smallTool->writeFile(data, filePathInput);
}
//结构体名映射id
void MainWindow::changeNameToId()
{
    int len = _parseHeadMsgList.length();

    for(int i=0; i<len;i++){

        QVariantMap m = _parseHeadMsgList.at(i).toMap();

        QString name = m.value("name").toString();
        int id = m.value("id").toInt();

        _name_to_id.insert(name, id);
    }
}

//处理解析的头文件
void MainWindow::handleParseResult(QVariant data)
{
    _parseHeadMsgList = data.toList();

    changeNameToId();

    saveCommonJson();

    showData();
}

/*发送*/
void MainWindow::on_pushButton_clicked()
{
    //send
    QString data;
    int rowCount = _parseHeadMsgList.length();

    for(int i=0; i<rowCount; i++)
    {
        QVariantMap map = _parseHeadMsgList.at(i).toMap();
        if(map.value("isStop", true).toBool()){
            //停止报文
            continue;
        }
        QString structName = map.value("name").toString();    //结构体名
        QVariantList msgList = map.value("msgList").toList();
        int tempId = map.value("id").toInt();

        int len = 0;
        QByteArray one = changeToba(tempId, msgList, len);
        if(one.isEmpty()) continue;

        QByteArray temp;
        temp.append(tempId);
        temp.append(':');
        temp.append(len);
        temp.append(':');
        temp.append(one);
        temp.append('---');
        data += QString(temp.toHex());

//        if(tempId == MSG_EEPROM_1_ID)
//            qInfo()<<one<<len<<temp;

    }

    _smallTool->writeFile(data, filePathOutput);

    //pm
    QString datapm;
    datapm = "0:" + QString::number(_currentPM);
    _smallTool->writeFile(datapm, filePathpmOutput);
}

void MainWindow::on_action_edit_triggered()
{
    //edit show
    _edit_form->showWidget();
}

void MainWindow::on_action_help_triggered()
{
    //help
    _dialog_Help->show();
}

void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item)
{
    //点击结构体名字,显示结构体列表
    QString name = item->text();
    name = name.split(":")[0];

    int len = _parseHeadMsgList.length();

    for(int i=0; i<len;i++){

        QString fromName = _parseHeadMsgList.at(i).toMap().value("name").toString();

//        qInfo()<<"on_listWidget_itemClicked "<<i<<name<<fromName;
        if(name == fromName){

            //更新  停止报文 box
            ui->checkBox_2->setChecked(_parseHeadMsgList.at(i).toMap().value("isStop", true).toBool());

//            ui->tableWidget->clear();
            ui->tableWidget->setRowCount(0);

            QVariantList msgList = _parseHeadMsgList.at(i).toMap().value("msgList").toList();

            int l = msgList.length();

            ui->tableWidget->setRowCount(l);
//            qInfo()<<"--"<<l;

            for(int j=0; j<l; j++){
                QVariantMap m = msgList.at(j).toMap();
                QString msgName = m.value("name").toString();
                QString msgBits = QString::number(m.value("bits").toInt());
                QString msgValue = m.value("value").toString();
//                qInfo()<<j<<msgName;

                QTableWidgetItem* item1 = new QTableWidgetItem(msgName);
                QTableWidgetItem* item2 = new QTableWidgetItem(msgBits);
                QTableWidgetItem* item3 = new QTableWidgetItem(msgValue);

                item1->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
                item2->setFlags(Qt::NoItemFlags | Qt::ItemIsEnabled | Qt::ItemIsSelectable);

                ui->tableWidget->setItem(j, 0, item1);
                ui->tableWidget->setItem(j, 1, item2);
                ui->tableWidget->setItem(j, 2, item3);
            }
            break;
        }
    }
}

void MainWindow::on_tableWidget_cellChanged(int row, int column)
{
//    qInfo()<<"on_tableWidget_cellChanged "<<_currentStructIndex<<row<<column;
    //_currentStructIndex
    int index = -1;
    QString structName = ui->listWidget->currentItem()->text();
    structName = structName.split(":")[0];

    int len = _parseHeadMsgList.length();
    for(int i=0; i<len; i++){
        if( _parseHeadMsgList.at(i).toMap().value("name").toString() == structName){
            index = i;
            break;
        }
    }

    if(index == -1) return;

    QVariantMap map = _parseHeadMsgList.at(index).toMap();
    QVariantList msgList = map.value("msgList").toList();
    QVariantMap m = msgList.at(row).toMap();

    if(column  == 0){
        m.insert("name", ui->tableWidget->item(row, column)->text());
    }
    else if(column  == 1){
        m.insert("bits", ui->tableWidget->item(row, column)->text().toInt());
    }
    else if(column  == 2){
        m.insert("value", ui->tableWidget->item(row, column)->text().toDouble());
    }
    msgList[row] = m;
    map.insert("msgList", msgList);
    _parseHeadMsgList[index] = map;
}

void MainWindow::on_action_onLine_triggered()
{
    //下线配置计算工具
    _dialog_Config->show();
}

void MainWindow::on_checkBox_stateChanged(int arg1)
{
    //实时发送
    if(arg1 == 0){
        //off
        m_timer->stop();
    }
    else{
        //on
        m_timer->start();
    }
}

void MainWindow::on_actionpop_triggered()
{
    _smallTool->checkPop();
}

void MainWindow::on_checkBox_2_stateChanged(int arg1)
{
    int index = ui->listWidget->currentRow();
    if(index < 0) return;

    QString structName = ui->listWidget->currentItem()->text();

    structName = structName.split(":")[0];

    int len = _parseHeadMsgList.length();
    for(int i=0; i<len; i++){
        if( _parseHeadMsgList.at(i).toMap().value("name").toString() == structName){
            index = i;
            break;
        }
    }

    if(index == -1) return;

    QVariantMap map = _parseHeadMsgList.at(index).toMap();

    //停止报文
    if(arg1 == 0){
        //循环报文
        map.insert("isStop", false);
    }
    else{
        //停止报文
        map.insert("isStop", true);
    }
    _parseHeadMsgList[index] = map;
}
